const WebSocket = require('ws');
const http = require('http');
const server = http.createServer();
const wss = new WebSocket.Server({ server });

const rooms = {};

wss.on('connection', (socket) => {
  socket.on('message', (data) => {
    const message = JSON.parse(data);
    if (message.type === 'createRoom') {
      const roomId = generateUniqueId(); // 生成唯一房间ID
      rooms[roomId] = [];
      socket.send(JSON.stringify({ type: 'roomCreated', roomId }));
    } else if (message.type === 'joinRoom') {
      const roomId = message.roomId;
      if (rooms[roomId]) {
        rooms[roomId].push(socket);
        socket.send(JSON.stringify({ type: 'joinedRoom', roomId }));
      }
    }
  });

  socket.on('close', () => {
    // 在房间中移除断开的 socket
    for (const roomId in rooms) {
      rooms[roomId] = rooms[roomId].filter(s => s !== socket);
    }
  });
});

server.listen(3000, () => {
  console.log('WebSocket server listening on port 3000');
});